//<%--子项状态、件数、重量、单价（含税）、货款金额、品名、牌号、规格、产地、技术标准、质量等级、件重、金额总计、
// 交货方式、税率、质保书份数、供应商合同子项号、资源号、采购合同子项号、备注。--%>
function getContractSubOptions(editFlag) {
    var initOptions = {
        idField: 'cid',
        fitColumns: false,
        width: 1700,
        checkOnSelect: false,
        singleSelect: false,
        fit: false,
        columns: [[{
            width: 20,
            checkbox: true
        }, {
            field: 'subContractCode',
            title: '采购合同子项号',
            width: 110
        }, {
            title: '子项状态',
            field: 'statusSub',
            width: 60
        }, {
            title: '件数',
            field: 'numberPage',
            width: 60,
            editor: {
                type: 'numberbox'
            }
        }, {
            field: 'weight',
            title: '<label class="redSharp">*重量</label>',
            width: 80,
            editor: {
                type: 'numberbox',
                options: {
                    precision: 6,
                    required: true,
                    validType: 'noEmptyNumber'
                }
            },
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatWeight(value);
            }
        }, {
            field: 'unitPrice',
            title: '<label class="redSharp">*单价(含税)</label>',
            width: 80,
            editor: {
                type: 'numberbox',
                options: {
                    precision: 2,
                    required: true,
                    validType: 'noEmptyNumber'
                }
            },
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'paymentAmount',
            title: '货款金额',
            width: 80,
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'f_pm_id',
            title: '<label class="redSharp">*品名</label>',
            width: 120,
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return rowData.goodsName;
            },
            editor: {
                type: 'combotree',
                options: {
                    required: true,
                    data: treeData,
                    textField: 'text',
                    onlyLeafCheck: true,
                    onBeforeSelect: function (node) {
                        var t = $(this).tree;
                        var isLeaf = t('isLeaf', node.target);
                        if (!isLeaf) {//选择的不是叶子节点
                            return false;
                        }
                    },
                    onClick:function(node){  //处理双击事件
                        var $this = $(this);
                        var target = node.target;
                        if( $this.tree('getChildren',target).length ){ //只对有子节点的节点做处理
                            $this.tree("toggle",target);
                            //黑魔法
                            $('td>.combo>span>span').click();
                        }
                    },
                    onHidePanel: function (node) {

                    }
                }
            }
        }, {
            field: 'marks',
            title: '<label class="redSharp">*牌号</label>',
            width: 60,
            editor: {
                type: 'validatebox',
                options: {
                    required: true
                }
            }
        }, {
            field: 'cpspecification',
            title: '<label class="redSharp">*规格</label>',
            width: 80,
            editor: {
                type: 'validatebox',
                options: {
                    required: true
                }
            }
        }, {
            field: 'f_cd_id',
            title: '<label class="redSharp">*产地</label>',
            width: 60,
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                for (var i = 0; i < address.length; i++) {
                    if (address[i].id == value) {
                        return address[i].orName;
                    }
                }
            },
            editor: {
                type: 'combobox',
                options: {
                    required: true,
                    data: address,
                    valueField: 'id',
                    textField: 'orName',
                    editable: false
                }
            }
        }, {
            field: 'standards',
            title: '技术标准',
            width: 60,
            editor: {
                type: 'text'
            }
        }, {
            field: 'qualityGrade',
            title: '质量等级',
            width: 60,
            editor: {
                type: 'text'
            }
        }, {
            field: 'unitWeight',
            title: '件重',
            width: 60,
            editor: {
                type: 'numberbox',
                options: {
                    precision: 6
                }
            },
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatWeight(value);
            }
        }, {
            field: 'totalCost',
            title: '金额总计',
            width: 80,
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'deliveryMethod',
            title: '*交货方式',
            width: 60,
            editor: {
                type: 'validatebox',
                options: {
                    required: true
                }
            }
        }, {
            field: 'subtaxAmount',
            width: 80,
            title: '税额',
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'taxRate',
            width: 40,
            title: '税率',
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'qualityNum',
            title: '质保书份数',
            width: 70,
            editor: {
                type: 'text'
            }
        }, {
            field: 'appSubContract',
            title: '供应商合同子项号',
            width: 110,
            editor: {
                type: 'text'
            }
        }, {
            field: 'resourceNumber',
            title: '资源号',
            width: 60,
            editor: {
                type: 'text'
            }
        }, {
            field: 'remark',
            title: '备注',
            width: 60,
            editor: {
                type: 'text'
            }
        }, {
            hidden: 'true',
            field: 'cdName',
            title: '产地名称',
            width: 60
        }, {
            hidden: 'true',
            field: 'goodsName',
            title: '品种名称',
            width: 60
        }]],
        toolbar: [{
            id: "addSub",
            text: '新增子项',
            iconCls: 'icon-add',
            handler: function () {
                addContract();
            }
        }, '-', {
            id: "deleteSub",
            text: '删除子项',
            iconCls: 'icon-remove',
            handler: function () {
                delContractSubIterm();
            }
        }, {
            id: "goodsFinish",
            text: '收货完成',
            iconCls: 'icon-remove'
        }, {
            id: "cancelGoodsFinish",
            text: '收货完成撤销',
            iconCls: 'icon-remove'
        }, {
            id: "settlementCompletion",
            text: '结算完成',
            iconCls: 'icon-remove'
        }, {
            id: "cancelSettlementCompletion",
            text: '结算完成撤销',
            iconCls: 'icon-remove'
        }],
        onClickCell: onClickCell,
        onAfterEdit: function (rowIndex, rowData, changes) {
            calculateContractSub(rowIndex, rowData);
            calculateToTop();
        }
    }
    if(!editFlag){
        initOptions.columns[0][1].hidden = 'true';
    }
    return initOptions;
}

function onClickCell(index, field) {
    if (endEditing($('#subItem'))) {
        if (checkLineStatus($('#subItem'), index)) {
            $('#subItem').datagrid('selectRow', index)
                .datagrid('editCell', {index: index, field: field});
            var ed = $('#subItem').datagrid('getEditor', {index: index, field: field});
            if (ed && ed.target) {
                $(ed.target).focus();
            }
            editIndex = index;
        }
    }
}
function checkLineStatus(node, index) {
    var rows = node.datagrid('getRows');
    if (rows && rows[index]) {
        if (!rows[index].statusSub) {
            return true;
        }
        if (rows[index].statusSub != "执行") {
            return false;
        } else {
            return true;
        }
    }
}

////货款金额等于重量*单价（含税），金额总计等于货款金额+运杂费，税率取系统配置项
function calculateContractSub(rowIndex, rowData) {
    // 得到columns对象
    var columns = $('#subItem').datagrid("options").columns;
// 得到rows对象
    var rows = $('#subItem').datagrid("getRows"); // 这段代码是// 对某个单元格赋值
    var payMoney = (rowData.weight ? rowData.weight : 0) * (rowData.unitPrice ? rowData.unitPrice : 0)
    var index = getColumnIndex(columns[0], "paymentAmount");
    var baseIndex = index ? index : 0;

    rows[rowIndex][columns[0][baseIndex].field] = payMoney.toFixed(2);
    //为运杂费预留
    rows[rowIndex][columns[0][getColumnIndex(columns[0], "totalCost")].field] = parseFloat(payMoney.toFixed(2));
    //税额
    var subtaxAmount = calculateTax(payMoney, rowData.taxRate);
    rows[rowIndex][columns[0][getColumnIndex(columns[0], "subtaxAmount")].field] = parseFloat(subtaxAmount.toFixed(2));
    //产地
    rows[rowIndex][columns[0][getColumnIndex(columns[0], "cdName")].field] = getComboboxText(address, rowData.f_cd_id);
    //品名
    if (rowData.f_pm_id) {
        rows[rowIndex][columns[0][getColumnIndex(columns[0], "goodsName")].field] = getComboTreeText(treeData, rowData.f_pm_id);
    }

// 刷新该行, 只有刷新了才有效果
    $('#subItem').datagrid('refreshRow', rowIndex);

}

var heTongStatus = getStatusData("/global/contractStatus.html");
function prepareContractSubmitPostData(flag) {
    endEditing($('#subItem'));
    var contractData = {};
    var postData = $('#searchForm-small').serializeJson();
    //状态码
    postData.contractStatus = changeStatusVal($('#contractStatus').val(), heTongStatus);
    if (flag == undefined) {
        //签约用户姓名
        var userNameRow = $('#userName').combogrid('grid').datagrid('getSelected');
        //商户代码 商户名称
        var menberNoRow = $('#memberNo').combogrid('grid').datagrid('getSelected');
        postData.userName = userNameRow.trueName;
        postData.providerName = menberNoRow.memberName;
        postData.providerCode = menberNoRow.memberNo;
    } else {
        postData.id = $('#contractId').text();
    }
    postData.contractDate = $('#contractDate').datebox("getText");
    //子项表数据
    var subRows = getUsefulRows($('#subItem').datagrid('getRows'));

    //数据主体结构
    contractData.contract = postData;
    contractData.contractSubList = subRows;
    return contractData;
}

function prepareContractSubmitRealPostData(flag) {
    var data = prepareContractSubmitPostData(flag);
    $.each(data.contractSubList, function (index, value) {
        value.statusSub = changeStatusVal(value.statusSub, heTongStatus);
        delete value.cid;
    });
    return data;
}

//刷新采购申请页面
function refreshContractPage(data) {
    //上部init
    loadData(data.object.contract);
    $('#totalAmount').numberbox('setValue',data.object.contract.totalAmount);
    $('#totalWeight').numberbox('setValue',data.object.contract.totalWeight);
    $('#taxGoodsAmount').numberbox('setValue',data.object.contract.taxGoodsAmount);
    $('#taxAmount').numberbox('setValue',data.object.contract.taxAmount);
    $('#contractDate').datebox({
        required: true,
        editable: false
    });
    $('#contractDate').datebox("setValue", data.object.contract.contractDate);
    //下部init
    if (data.object.contract.id) {
        var options = getContractSubOptions("edit");
    } else {
        var options = getContractSubOptions();
    }

    options.data = data.object.contractSubList;
    $.each(options.data, function (index, value) {
        value.cid = UUID();
    })
    initDataGridNoPager($('#subItem'), options);
    setContractAddButtonsStatus(data.object.contract.contractStatus);
}

//15、执行状态的采购合同可以新增子项、删除子项。
//16、采购合同子项做过入库后，不能再删除子项，需先撤销入库单。
//17、采购合同所有子项状态置为“收货完成”后，采购合同状态置为“收货完成”；
//采购合同所有子项状态置为“结算完成”后，采购合同状态置为“结算完成”。
//18、只有状态为“收货完成”且做过结算的采购合同子项，才能做结算完成。
//19、只有状态为“执行”，且做过入库的采购合同子项，才能做收货完成。
//20、“收货完成”状态的采购合同子项不允许再做入库。

function setContractAddButtonsStatus(status) {
    var nodeArray = [$("#addSub"), $("#deleteSub"), $("#goodsFinish"),
        $("#cancelGoodsFinish"), $("#settlementCompletion"),
        $("#cancelSettlementCompletion"),
        $("#editContractFunction"),
        $("#printContractFunction")];
    if (status === "执行") {
        setLinkButtonStatus(nodeArray, [1, 1, 1, 0, 1, 0, 1, 1]);
    } else if (status === "撤销") {
        setLinkButtonStatus(nodeArray, [0, 0, 0, 0, 0, 0, 0, 1]);
    } else if (status === "入库完成") {
        setLinkButtonStatus(nodeArray, [0, 0, 0, 1, 1, 0, 0, 1]);
    } else if (status === "结算完成") {
        setLinkButtonStatus(nodeArray, [0, 0, 0, 0, 0, 1, 0, 1]);
    }
}


function getContractDetail(data) {
    parent.$.modalDialog.handler.dialog('close');
    var options = {"id": data.object.contract.id};
    editContractFunction(options);
}


//为$('#subItem') 增加子项
function addContract() {
    $('#subItem').datagrid('uncheckAll');
    var row = {
        cid: UUID(),
        deliveryMethod: "自提",
        taxRate: "0.17",
        statusSub: "执行"
    };
    $('#subItem').datagrid('appendRow', row);
    $('#subItem').datagrid('checkRow', $('#subItem').datagrid('getRows').length - 1);
}

//删除子项
function delContractSubIterm() {
    var rows = $('#subItem').datagrid('getChecked');
    var cunzaiIds = [];
    var ids = [];
    if (rows.length > 0) {
        $.each(rows, function (index, value) {
            if (value.id) {
                cunzaiIds.push(value.id);
            }
            ids.push(value.cid);
        });
        if (cunzaiIds.length > 0) {
            $.messager.confirm('请确认', '您要删除当前所选项目,子项全部删除合同将被撤销？', function (r) {
                if (r) {
                    var postData = {
                        'contractId': $("#contractId").text(),
                        'contractSubIds': cunzaiIds
                    }
                    $.ajax({
                        type: "post",
                        data: JSON.stringify(postData),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        url: getContextPath() + "/purchase/deleteOneContractSub.html",
                        before: function () {
                            parent.$.messager.progress({
                                title: '提示',
                                text: '数据处理中，请稍后....'
                            });
                        },
                        success: function (data) {
                            parent.$.messager.progress('close');
                            if (data && isSuccess(data.result)) {
                                refreshContractPage(data);
                                //if(parent.$.modalDialog.openner_treeGrid){
                                //    parent.$.modalDialog.openner_treeGrid.datagrid('getPager').pagination('select');
                                //}
                            }
                        },
                        error: function () {
                            parent.$.messager.progress('close');
                            $.messager.alert('提示', '记录删除失败！', 'error');
                        }
                    });
                    calculateToTop();
                }
            });
        } else if (ids.length > 0) {
            $.messager.confirm('请确认', '您要删除当前所选项目？', function (r) {
                if (r) {
                    $.each(ids, function (index, value) {
                        $('#subItem').datagrid('deleteRow', $('#subItem').datagrid('getRowIndex', value));
                    });
                    calculateToTop();

                }
            });
        } else {
            $.messager.alert('提示', '请选择要删除的记录！', 'error');
        }
    }
}


